package com.hmall.search;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.feign.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.search.constant.EsConstant;
import com.hmall.search.pojo.ItemDto;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;
@Slf4j
@SpringBootTest
public class ItemSearApplicationtext {

    @Autowired
    private ItemClient itemClientclient;

    @Autowired
    private RestHighLevelClient client;

    @Test
    public void importData() throws Exception {
        int page=1;
        ObjectMapper objectMapper = new ObjectMapper();
        while (true) {
            BulkRequest bulkRequest = new BulkRequest();

            PageDTO<Item> pageDTO = itemClientclient.list(page,200);
            List<Item> list = pageDTO.getList();
            if (list.size() <= 0) {
                break;
            }
            for (Item item : list) {
                ItemDto itemDto = new ItemDto(item);
                bulkRequest.add(new IndexRequest(EsConstant.Itme_INDEX)
                        .id(itemDto.getId().toString())
                        .source(objectMapper.writeValueAsString(itemDto), XContentType.JSON)
                );
            }
          client.bulk(bulkRequest,RequestOptions.DEFAULT);
            page++;
        }
        log.warn("数据已经导入...");
    }

}
